package resoft.jeasyform.components;

import charvax.swing.JButton;
import resoft.jeasyform.event.EventHandler;
import resoft.jeasyform.event.EventType;
import charva.awt.event.ActionListener;
import charva.awt.event.ActionEvent;

/**
 * <p></p>
 * User: albert
 * Date: Aug 26, 2007
 * Time: 7:52:04 PM
 */
public class Button extends Component implements AcceptFocusAware{
    public Button() {
        init();
    }

    public Button(String text) {
        init();
        setText(text);
    }

    private void init() {
        setAcceptFocus(true);
    }


    public charva.awt.Component getSwingObject() {
        jButton = new JButton(text);
        jButton.setBounds(getY(),getX(),getY() + getHeight(),getX() + getWidth());
        
        jButton.addActionListener(new ButtonActionListener(getParentWindow(),this,clickedEventHandler));
        return jButton;
    }

    /**
     * hide
     */
    public void hide() {
        jButton.setVisible(false);
        setAcceptFocus(false);
    }

    /**
     * show
     */
    public void show() {
        jButton.setVisible(true);
        setAcceptFocus(true);
    }

    /**
     * actionListner adapter
     * */
    class ButtonActionListener implements ActionListener {
        public ButtonActionListener(Window parentWindow,Button button,EventHandler handler) {
            this.parentWindow = parentWindow;
            this.button = button;
            this.handler = handler;
        }

        public void actionPerformed(ActionEvent actionEvent) {
            handler.execute(parentWindow,button, EventType.EVENT_CLICKED);
        }
        private Window parentWindow;
        private Button button;
        private EventHandler handler;
    }




    public void setText(String text) {
        this.text = text;
    }

    public void registerClickedEvent(EventHandler handler) {
        if(handler!=null) {
            this.clickedEventHandler = handler;
        }                                              
    }

    public void requestFocus() {
        jButton.requestFocus();
    }

    private String text;

    private JButton jButton;
    private EventHandler clickedEventHandler = new EventHandler() {

        public boolean execute(Window window, Component source, int eventType) {
            return true;
        }
    };
}
